<template>
  <div>
    <el-upload
      action
      list-type="picture-card"
      :class="{disabled:fileList.length > 0}"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :on-change="handleChange"
      :http-request="handleHttpRequest"
      :before-upload="handleBeforeUpload"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-progress v-if="uploading" :percentage="percent" style="width:197px"></el-progress>
    <el-dialog :visible.sync="dialogVisible" title="图片预览">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>

var COS = require('cos-js-sdk-v5')
// SECRETID 和 SECRETKEY 请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDCE2c091h9LGzJPFo7BzVllX2GvLXT9Zh',
  SecretKey: 'xe7NVZfZEd5XnoCQTNAl9RV5QglfNqAD'
})
export default {
  name: 'ImageUpload',
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      uploading: false,
      percent: 0
    }
  },
  methods: {
    // 删除图片
    handleRemove(file, fileList) {
      console.log(file, fileList)
      const index = this.fileList.findIndex(el => el.uid === file.uid)
      this.fileList.splice(index, 1)
    },
    // 图片弹窗
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 上传文件函数
    handleChange({ raw }, fileList) { },
    handleHttpRequest({ file }) {
      this.fileList = [{ url: window.URL.createObjectURL(file) }]
      // 拿到文件对象
      // 上传对象
      this.uploading = true
      cos.uploadFile({
        Bucket: 'photo-1317097642', /* 填写自己的 bucket，必须字段 */
        Region: 'ap-chengdu', /* 存储桶所在地域，必须字段 */
        Key: Date.now() + file.name, /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        Body: file, // 上传文件对象
        SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: (progressData) => {
          // console.log(JSON.stringify(progressData))
          this.percent = parseInt(progressData.percent * 100)
        }
      }, (err, data) => {
        if (err) {
          console.log('上传失败', err)
        } else {
          console.log('上传成功', data)
          // 把图片结果给组件
          this.fileList[0].url = 'http://' + data.Location
        }
        this.uploading = false
      })
    },
    handleBeforeUpload({ size, type }) {
      if (!['image/gif', 'image/jpeg', 'image/png'].includes(type)) {
        this.$message.error('文件类型错误')
        return false
      }
      if (size > 5 * 1024 * 1024) {
        this.$message.error('文件体积过大')
        return false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .disabled .el-upload--picture-card{
    display: none;
}
</style>
